const App = getApp()

Page({
  data: {
    carts: [], // 购物车列表
    hasList: false, // 列表是否有数据
    totalPrice: 0, // 总价，初始为0
    selectAllStatus: true, // 全选状态，默认全选
    hidden: !0,
    address: {
      item: {},
    }
  },
  onLoad(option) {
    console.log(option)
    this.setData({
      address_id: option.id
    })

    const carts = {
      items: App.WxService.getStorageSync('confirmOrder'),
      totalAmount: 0,
    }
    this.setData({
      carts: carts
    })

    console.log(this.data.carts)
  },
  onShow() {
    const address_id = this.data.address_id
    if (address_id) {
      this.getAddressDetail(address_id)
    } else {
      this.getDefalutAddress()
    }
  },
  redirectTo(e) {
    console.log(e)
    App.WxService.redirectTo('/pages/address/confirm/index', {
      ret: this.data.address_id
    })
  },
  getDefalutAddress() {
    App.HttpService.getDefalutAddress()
      .then(res => {
        const data = res.data
        console.log(data)
        if (data.meta.code == 0) {
          this.setData({
            address_id: data.data._id,
            'address.item': data.data,
          })
        } else {
          this.showModal()
        }
      })
  },
  showModal() {
    App.WxService.showModal({
        title: '友情提示',
        content: '没有收货地址，请先设置',
      })
      .then(data => {
        console.log(data)
        if (data.confirm == 1) {
          App.WxService.redirectTo('/pages/address/add/index')
        } else {
          App.WxService.navigateBack()
        }
      })
  },
  getAddressDetail(id) {
    App.HttpService.getAddressDetail(id)
      .then(res => {
        const data = res.data
        console.log(data)
        if (data.meta.code == 0) {
          this.setData({
            'address.item': data.data
          })
        }
      })
  },
  addOrder() {
    const address_id = this.data.address_id
    const params = {
      items: [],
      address_id: address_id,
    }
    this.data.carts.items.forEach(n => {
      params.items.push({
        id: n.goods._id,
        total: n.total,
      })
    })
    console.log(params)
    App.HttpService.postOrder(params)
      .then(res => {
        const data = res.data
        console.log(data)
        if (data.meta.code == 0) {
          App.WxService.redirectTo('/pages/order/detail/index', {
            id: data.data._id
          })
        }
      })
  },
  clear() {
    App.HttpService.clearCartByUser()
      .then(res => {
        const data = res.data
        console.log(data)
      })
  },
  onShow() {
    this.setData({
      hasList: true,
      carts: [{
        id: 1,
        title: '限时购微信小程序限时开发七日方案A',
        image: '/assets/Rectangle2@2x.png',
        num: 1,
        price: 999.00,
        selected: true
      }, ]
    });
    this.getTotalPrice();
  },
  /**
   * 当前商品选中事件
   */
  selectList(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    const selected = carts[index].selected;
    carts[index].selected = !selected;
    this.setData({
      carts: carts
    });
    this.getTotalPrice();
  },

  /**
   * 删除购物车当前商品
   */
  deleteList(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    carts.splice(index, 1);
    this.setData({
      carts: carts
    });
    if (!carts.length) {
      this.setData({
        hasList: false
      });
    } else {
      this.getTotalPrice();
    }
  },

  /**
   * 购物车全选事件
   */
  selectAll(e) {
    let selectAllStatus = this.data.selectAllStatus;
    selectAllStatus = !selectAllStatus;
    let carts = this.data.carts;

    for (let i = 0; i < carts.length; i++) {
      carts[i].selected = selectAllStatus;
    }
    this.setData({
      selectAllStatus: selectAllStatus,
      carts: carts
    });
    this.getTotalPrice();
  },

  /**
   * 绑定加数量事件
   */
  addCount(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    let num = carts[index].num;
    num = num + 1;
    carts[index].num = num;
    this.setData({
      carts: carts
    });
    this.getTotalPrice();
  },

  /**
   * 绑定减数量事件
   */
  minusCount(e) {
    const index = e.currentTarget.dataset.index;
    const obj = e.currentTarget.dataset.obj;
    let carts = this.data.carts;
    let num = carts[index].num;
    if (num <= 1) {
      return false;
    }
    num = num - 1;
    carts[index].num = num;
    this.setData({
      carts: carts
    });
    this.getTotalPrice();
  },

  /**
   * 计算总价
   */
  getTotalPrice() {
    let carts = this.data.carts; // 获取购物车列表
    let total = 0;
    for (let i = 0; i < carts.length; i++) { // 循环列表得到每个数据
      if (carts[i].selected) { // 判断选中才会计算价格
        total += carts[i].num * carts[i].price; // 所有价格加起来
      }
    }
    this.setData({ // 最后赋值到data中渲染到页面
      carts: carts,
      totalPrice: total.toFixed(2)
    });
  }
})